package com.sds.system.services;

import com.estontorise.gae_filestore.FileStoreFactory;
import com.estontorise.gae_filestore.interfaces.DataStoreFile;
import com.estontorise.gae_filestore.interfaces.FileStore;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

@Singleton
public class FileManager {
    private FileStore fileStore = FileStoreFactory.getFileStore();

    @Inject
    public FileManager() {
    }


    public DataStoreFile getFile(String path) throws IOException {
        return getFile(path, false);
    }

    public DataStoreFile getFile(String path, boolean reset) throws IOException {
        DataStoreFile dataStoreFile = fileStore.getFile(path, false);
        if (!dataStoreFile.exists() || reset) {
            URL resourceUrl = getClass().getResource(path);
            if (resourceUrl != null) {
                dataStoreFile = fileStore.getFile(path, true);
                InputStream inputStream = resourceUrl.openStream();
                OutputStream tempOutputStream = dataStoreFile.openForWrite();
                IOUtils.copy(inputStream, tempOutputStream);
                IOUtils.closeQuietly(tempOutputStream);
            }
        }
        return dataStoreFile;
    }
}
